#include <stdio.h>
#include <stdlib.h>
#include "edge.h"
#include "edge_list.h"


EdgeList * newEdgeList(){
	EdgeList * el = (EdgeList *)malloc(sizeof(EdgeList));
	el->edges = NULL;
	el->length = 0;
	return el;
}

Edge * addEdgeToList(Edge * list, Edge * e){
	if(list == NULL){
		e->next = NULL;
		return e;
	}
	else{
		list->next = addEdgeToList(list->next,e);
		return list;
	}
}

Edge * addAllEdgesToList(Edge * list, Edge * e){
	if(list == NULL){
		return e;
	}
	else{
		list->next = addAllEdgesToList(list->next,e);
		return list;
	}
}

Edge * removeEdgeFromList(Edge * list, Edge * e){
	if(list != NULL){
		if(compareEdge(list,e)){
			return list->next;
		}
		else{
			list->next = removeEdgeFromList(list->next,e);
			return list;
		}
	}
	return list;
}

Edge * removeEdgeByIndex(Edge * list, int index){
	if(list != NULL){
		if(index == 0){
			return list->next;
		}
		else{
			index--;
			list->next = removeEdgeByIndex(list->next,index);
			return list;
		}
	}
	return list;
}

int containsEdgeInList(Edge * list, Edge * e){
	if(list != NULL){
		if(compareEdge(list,e)){
			return 1;
		}
		else{
			return containsEdgeInList(list->next,e);
		}
	}
	else
		return 0;
}

void printEdgeList(EdgeList * el){
	Edge * e = el->edges;
	int index=0;
	printf("EDGELIST\n===============\n");
	while(e != NULL){
		printf("%d. Edge P1[%g,%g], P2[%g,%g]\n", index++, e->a->x, e->a->y, e->b->x, e->b->y);
		e = e->next;
	}
	printf("==============\n");
}

void freeEdges(Edge * list){
	if(list != NULL){
		freeEdges(list->next);
		freeEdge(list);
	}
}

void freeEdgeList(EdgeList * el){
	freeEdges(el->edges);
	free(el);
}

void addEdge(EdgeList * el,  Edge *e){
	el->edges = addEdgeToList(el->edges,e);
	el->length++;
}

void addAllEdges(EdgeList * el1, EdgeList * el2){
    el1->edges = addAllEdgesToList(el1->edges, el2->edges);
    el1->length += el2->length;
}

void deleteEdge(EdgeList * el, Edge * e){
	el->edges = removeEdgeFromList(el->edges,e);
	el->length--;
}

int containsEdge(EdgeList * el, Edge * e){
	return containsEdgeInList(el->edges,e);
}

void deleteEdgeByIndex(EdgeList * el, int index){
	el->edges = removeEdgeByIndex(el->edges,index);
	el->length--;
}

int edgeListContainsPoint(EdgeList * list, Point * p){
	Edge * edge = list->edges;
	while(edge != NULL){
		if(compare(edge->a, p) == 0)
			return 1;
		if(compare(edge->b, p) == 0)
			return 1;
		edge = edge->next;
	}
	return 0;
}


//int main(){
//    printf("EDGE_LIST");
//    EdgeList * el = newEdgeList();
//    int i=0;
//    for(i=0; i<20; i++){
//        Edge * e = newEdge();
//        addEdge(el,e);
//    }
//    printf("ELEMENTS: %d", el->length);
//
//
//    freeEdgeList(el);
//    printf("FREE");
//}

